package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysClasses;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.mapper.SysClassesMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysClassesService;

/**
 * 班级管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysClassesServiceImpl implements ISysClassesService
{
    @Autowired
    private SysClassesMapper classesMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    /**
     * 查询班级管理数据
     * 
     * @param classes 班级信息
     * @return 班级信息集合
     */
    @Override
    @DataScope(classesAlias = "d")
    public List<SysClasses> selectClassesList(SysClasses classes)
    {
        return classesMapper.selectClassesList(classes);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param classess 班级列表
     * @return 树结构列表
     */
    @Override
    public List<SysClasses> buildClassesTree(List<SysClasses> classess)
    {
        List<SysClasses> returnList = new ArrayList<SysClasses>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysClasses classes : classess)
        {
            tempList.add(classes.getClassesId());
        }
        for (Iterator<SysClasses> iterator = classess.iterator(); iterator.hasNext();)
        {
            SysClasses classes = (SysClasses) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(classes.getParentId()))
            {
                recursionFn(classess, classes);
                returnList.add(classes);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = classess;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param classess 班级列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildClassesTreeSelect(List<SysClasses> classess)
    {
        List<SysClasses> classesTrees = buildClassesTree(classess);
        return classesTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询班级树信息
     * 
     * @param roleId 角色ID
     * @return 选中班级列表
     */
    @Override
    public List<Integer> selectClassesListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return classesMapper.selectClassesListByRoleId(roleId, role.isClassesCheckStrictly());
    }

    /**
     * 根据班级ID查询信息
     * 
     * @param classesId 班级ID
     * @return 班级信息
     */
    @Override
    public SysClasses selectClassesById(Long classesId)
    {
        return classesMapper.selectClassesById(classesId);
    }

    /**
     * 根据ID查询所有子班级（正常状态）
     * 
     * @param classesId 班级ID
     * @return 子班级数
     */
    @Override
    public int selectNormalChildrenClassesById(Long classesId)
    {
        return classesMapper.selectNormalChildrenClassesById(classesId);
    }

    /**
     * 是否存在子节点
     * 
     * @param classesId 班级ID
     * @return 结果
     */
    @Override
    public boolean hasChildByClassesId(Long classesId)
    {
        int result = classesMapper.hasChildByClassesId(classesId);
        return result > 0 ? true : false;
    }

    /**
     * 查询班级是否存在用户
     * 
     * @param classesId 班级ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkClassesExistUser(Long classesId)
    {
        int result = classesMapper.checkClassesExistUser(classesId);
        return result > 0 ? true : false;
    }

    /**
     * 校验班级名称是否唯一
     * 
     * @param classes 班级信息
     * @return 结果
     */
    @Override
    public String checkClassesNameUnique(SysClasses classes)
    {
        Long classesId = StringUtils.isNull(classes.getClassesId()) ? -1L : classes.getClassesId();
        SysClasses info = classesMapper.checkClassesNameUnique(classes.getClassesName(), classes.getParentId());
        if (StringUtils.isNotNull(info) && info.getClassesId().longValue() != classesId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验班级是否有数据权限
     * 
     * @param classesId 班级id
     */
    @Override
    public void checkClassesDataScope(Long classesId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysClasses classes = new SysClasses();
            classes.setClassesId(classesId);
            List<SysClasses> classess = SpringUtils.getAopProxy(this).selectClassesList(classes);
            if (StringUtils.isEmpty(classess))
            {
                throw new ServiceException("没有权限访问班级数据！");
            }
        }
    }

    /**
     * 新增保存班级信息
     * 
     * @param classes 班级信息
     * @return 结果
     */
    @Override
    public int insertClasses(SysClasses classes)
    {
        SysClasses info = classesMapper.selectClassesById(classes.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("班级停用，不允许新增");
        }
        classes.setAncestors(info.getAncestors() + "," + classes.getParentId());
        return classesMapper.insertClasses(classes);
    }

    /**
     * 修改保存班级信息
     * 
     * @param classes 班级信息
     * @return 结果
     */
    @Override
    public int updateClasses(SysClasses classes)
    {
        SysClasses newParentClasses = classesMapper.selectClassesById(classes.getParentId());
        SysClasses oldClasses = classesMapper.selectClassesById(classes.getClassesId());
        if (StringUtils.isNotNull(newParentClasses) && StringUtils.isNotNull(oldClasses))
        {
            String newAncestors = newParentClasses.getAncestors() + "," + newParentClasses.getClassesId();
            String oldAncestors = oldClasses.getAncestors();
            classes.setAncestors(newAncestors);
            updateClassesChildren(classes.getClassesId(), newAncestors, oldAncestors);
        }
        int result = classesMapper.updateClasses(classes);
        if (UserConstants.DEPT_NORMAL.equals(classes.getStatus()) && StringUtils.isNotEmpty(classes.getAncestors())
                && !StringUtils.equals("0", classes.getAncestors()))
        {
            // 如果该班级是启用状态，则启用该班级的所有上级班级
            updateParentClassesStatusNormal(classes);
        }
        return result;
    }

    /**
     * 修改该班级的父级班级状态
     * 
     * @param classes 当前班级
     */
    private void updateParentClassesStatusNormal(SysClasses classes)
    {
        String ancestors = classes.getAncestors();
        Long[] classesIds = Convert.toLongArray(ancestors);
        classesMapper.updateClassesStatusNormal(classesIds);
    }

    /**
     * 修改子元素关系
     * 
     * @param classesId 被修改的班级ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateClassesChildren(Long classesId, String newAncestors, String oldAncestors)
    {
        List<SysClasses> children = classesMapper.selectChildrenClassesById(classesId);
        for (SysClasses child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            classesMapper.updateClassesChildren(children);
        }
    }

    /**
     * 删除班级管理信息
     * 
     * @param classesId 班级ID
     * @return 结果
     */
    @Override
    public int deleteClassesById(Long classesId)
    {
        return classesMapper.deleteClassesById(classesId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysClasses> list, SysClasses t)
    {
        // 得到子节点列表
        List<SysClasses> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysClasses tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysClasses> getChildList(List<SysClasses> list, SysClasses t)
    {
        List<SysClasses> tlist = new ArrayList<SysClasses>();
        Iterator<SysClasses> it = list.iterator();
        while (it.hasNext())
        {
            SysClasses n = (SysClasses) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getClassesId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysClasses> list, SysClasses t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
